package com.zhuang.kmp;

/**
 * description: ViolentMatch
 * date: 2022/9/29 22:25
 * author: Zhuang
 * version: 1.0
 */
public class ViolentMatch {
    public static void main(String[] args) {
        String str1 = "好你好好好你";
        String str2 = "你好";
        int i = violentMatch(str1, str2);
        System.out.println("i = " + i);
    }

    /**
     * 暴力匹配测试
     *
     * @param str1 字符串
     * @param str2 字符串
     * @return int
     */
    public static int violentMatch(String str1, String str2) {
        char[] s1 = str1.toCharArray();
        char[] s2 = str2.toCharArray();

        int s1Len = s1.length;
        int s2Len = s2.length;
        // s1索引
        int i = 0;
        // s2索引
        int j = 0;
        while (i < s1Len && j < s2Len) {
            // 保证匹配时不越界
            if (s1[i] == s2[j]) {
                i++;
                j++;
            } else {
                // 没匹配成功
                i = i - (j - 1);
                j = 0;
            }
        }
        // 判断是否成功
        if (j == s2Len) {
            return i - j;
        } else {
            return -1;
        }
    }
}
